﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using XConductor.Domain.Seedwork.Media;

namespace XConductor.Domain.Shared.Media
{
    public class AudioDescriptionService : IAudioDescriptionService
    {
        private IDictionary<AudioFormats, IAudioFormatDescriptor> m_descriptors;
        
        public AudioDescriptionService(IDictionary<AudioFormats, IAudioFormatDescriptor> descriptors)
        {
            this.m_descriptors = descriptors;
        }

        public async Task<IAudioFormatDescription> GetFormatDescription(Stream stream)
        {
            IAudioFormatDescription description = null;

            foreach (IAudioFormatDescriptor descriptor in this.m_descriptors.Values)
            {
                description = await descriptor.GetFormatDescription(stream);
                
                if (description.IsValid()) 
                    break;
            }

            return description;
        }

        public async Task<IAudioFormatDescription> TryGetFormatDescription(Stream stream, AudioFormats format)
        {
            IAudioFormatDescriptor descriptor;

            if (this.m_descriptors.TryGetValue(format, out descriptor))
            {
                IAudioFormatDescription description = await descriptor.GetFormatDescription(stream);

                if (description.IsValid())
                {
                    return description;
                }
            }

            return null;
        }

        public void Dispose()
        {
            if (this.m_descriptors != null)
            {
                foreach (var descriptor in this.m_descriptors.Values) descriptor.Dispose();
            }
        }
    }
}
